using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bubble : MonoBehaviour
{
    private GameObject candy;
    private Rigidbody2D rb;
    private Rigidbody2D candyRb;

    // private Animator animator;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        // animator = GetComponent<Animator>();
        // animator.enabled = false;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log("OnTriggerEnter2D  Candy");
        // ! 层级会影响碰撞的触发
        if (collision.CompareTag("Candy"))
        {
            candy = collision.gameObject;

            // animator.enabled = true;
            candy.transform.position = transform.position;
            candyRb = candy.GetComponent<Rigidbody2D>();
            // 重力
            candyRb.gravityScale = 0;
            // 质量
            // candyRb.mass = 0.01f;
            // 不行: 使用 AddForce 施加力来移动/停止物体
            Vector2 upDirection = Vector2.up;
            // candyRb.AddForce(upDirection * 10f, ForceMode2D.Impulse); // 向上的力适得其反
            // 增加阻力可以
            candyRb.drag = 10f; // 增加阻力值，物体停下的速度更快,可以让物体慢下/停下
            // 停止物体的速度
            // candyRb.velocity = Vector2.zero;
            // 不太行,不稳定
            // candyRb.Sleep(); // 物体将不再受任何力的影响，速度和加速度为零

            // 不太行,不稳定;如果物体有速度，施加一个与速度方向相反的力来减速
            // if (candyRb.velocity.magnitude > 0)
            // {
            //     Vector2 oppositeForce = -candyRb.velocity.normalized * 2f; // 施加一个与速度方向相反的力
            //     candyRb.AddForce(oppositeForce, ForceMode2D.Force); // 使用持续的力逐渐减速
            // }
            rb.velocity = new Vector2(0, 1);
        }
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.CompareTag("Candy"))
        {
            Debug.Log("OnTriggerStay2D  Candy");
            candy.transform.position = transform.position;
        }
    }

    private void OnMouseDown()
    {
        Debug.Log("OnMouseDown"); // 会被误触，什么原因，如何解决？
        if (candyRb != null)
        {
            candyRb.velocity = new Vector2(0, 1);
            candyRb.gravityScale = 1;
            candyRb.drag = 0;
            gameObject.SetActive(false);
            Destroy(gameObject);
        }
    }
}
